package cn.tianyigps.tianyigpsynclean.dao;

import cn.tianyigps.tianyigpspublic.bean.EquipmentHistory;
import cn.tianyigps.tianyigpspublic.bean.EquipmentLastData;
import cn.tianyigps.tianyigpspublic.param.bo.EquipmentLongLat;
import cn.tianyigps.tianyigpspublic.param.bo.EquipmentParamBO;
import cn.tianyigps.tianyigpspublic.param.constant.CollectionNameConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;


/**
 * @Author: WEI.YUAN
 * @Descirption:
 * @Date: 2019/4/25_10:08
 */
@Repository
public class DataCleanDaoImpl implements DataCleanDao {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public EquipmentLastData findEqById(String eqId) {

        Query query = new Query(Criteria.where("equipmentId").is(eqId));
        List<EquipmentLastData> eqModels = mongoTemplate.find(query, EquipmentLastData.class, CollectionNameConstant.EQUIPMENT_LAST_DATA);
        EquipmentLastData eqmodel = null;
        if (!CollectionUtils.isEmpty(eqModels)) {
            eqmodel = eqModels.get(0);
        }
        return eqmodel;

    }

    @Override
    public void insertEquipmentHisttory(EquipmentHistory equipmentHistory, String collectionName) {
        mongoTemplate.insert(equipmentHistory, collectionName);
    }

    @Override
    public void insertEquipmentLast(EquipmentLastData equipmentLastData, String collectionName) {
        mongoTemplate.insert(equipmentLastData, collectionName);

    }

    @Override
    public void updateEquipmentLastData(EquipmentLastData equipmentLastData, String collectionName) {
        Query query = new Query();
        query.addCriteria(Criteria.where("equipmentId").is(equipmentLastData.getEquipmentId()));
        Update update = new Update();
        if (equipmentLastData.getSignalTime() != null) {
            update.set("signalTime", equipmentLastData.getSignalTime());
        }
        Map<String, EquipmentParamBO> params = equipmentLastData.getParams();
        Map<String, Object> maps = equipmentLastData.getMaps();
        if (!CollectionUtils.isEmpty(params)) {
            update.set("params", params);
        }
        if (!CollectionUtils.isEmpty(maps)) {
            update.set("maps", maps);
        }
        mongoTemplate.upsert(query, update, collectionName);
    }
}
